<template>
  <div class="appointment-management">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">日程管理</h1>
          <p class="page-subtitle">管理客户预约、待办事项和日程安排</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showAddDialog = true">
            <i class="fas fa-plus mr-2"></i>新建预约
          </el-button>
          <el-button type="success" @click="showAddTodoDialog = true">
            <i class="fas fa-tasks mr-2"></i>新建待办
          </el-button>
          <el-button @click="refreshData">
            <i class="fas fa-sync-alt mr-2"></i>刷新
          </el-button>
        </div>
      </div>
    </header>

    <!-- 日历视图切换 -->
    <div class="view-controls">
      <el-radio-group v-model="viewMode" class="view-mode-selector">
        <el-radio-button label="calendar">日历视图</el-radio-button>
        <el-radio-button label="list">预约列表</el-radio-button>
        <el-radio-button label="todos">待办事项</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon bg-blue-100">
            <i class="fas fa-calendar-alt text-blue-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ totalAppointments }}</h3>
            <p>总预约数</p>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon bg-orange-100">
            <i class="fas fa-clock text-orange-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ todayAppointments }}</h3>
            <p>今日预约</p>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon bg-green-100">
            <i class="fas fa-check-circle text-green-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ completedAppointments }}</h3>
            <p>已完成</p>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon bg-red-100">
            <i class="fas fa-exclamation-triangle text-red-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ urgentAppointments }}</h3>
            <p>紧急处理</p>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon bg-purple-100">
            <i class="fas fa-tasks text-purple-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ totalTodos }}</h3>
            <p>待办事项</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section" v-if="viewMode === 'list'">
      <div class="filter-content">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索客户姓名、预约编号..."
            size="large"
            clearable
          >
            <template #prefix>
              <i class="fas fa-search"></i>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="filters.status" placeholder="预约状态" clearable>
            <el-option label="待确认" value="pending"></el-option>
            <el-option label="已确认" value="confirmed"></el-option>
            <el-option label="进行中" value="in-progress"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
          
          <el-select v-model="filters.type" placeholder="预约类型" clearable>
            <el-option label="法律咨询" value="consultation"></el-option>
            <el-option label="案件委托" value="commission"></el-option>
            <el-option label="合同审查" value="contract"></el-option>
            <el-option label="其他服务" value="other"></el-option>
          </el-select>
          
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="clearFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 日历视图 -->
    <div v-if="viewMode === 'calendar'" class="calendar-section">
      <div class="calendar-container">
        <el-calendar v-model="selectedDate">
          <template #date-cell="{ data }">
            <div class="calendar-day">
              <div class="day-number">{{ data.day.split('-').slice(-1)[0] }}</div>
              <div class="appointments-count" v-if="getDayAppointments(data.day).length > 0">
                {{ getDayAppointments(data.day).length }}个预约
              </div>
            </div>
          </template>
        </el-calendar>
      </div>
    </div>

    <!-- 列表视图 -->
    <div v-if="viewMode === 'list'" class="appointment-list-section">
      <div class="appointment-table">
        <el-table :data="filteredAppointments" style="width: 100%" v-loading="loading">
          <el-table-column prop="appointmentNo" label="预约编号" width="140">
            <template #default="scope">
              <span class="font-medium text-blue-600 cursor-pointer" @click="viewAppointment(scope.row)">
                {{ scope.row.appointmentNo }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="clientName" label="客户姓名" width="120"></el-table-column>
          
          <el-table-column prop="type" label="预约类型" width="120">
            <template #default="scope">
              <el-tag :type="getTypeColor(scope.row.type)">
                {{ getTypeName(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="scheduledDate" label="预约时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.scheduledDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="duration" label="时长" width="80">
            <template #default="scope">
              {{ scope.row.duration }}分钟
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusColor(scope.row.status)">
                {{ getStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="contact" label="联系方式" width="130"></el-table-column>
          
          <el-table-column label="操作" width="240" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="viewAppointment(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="confirmAppointment(scope.row)" v-if="scope.row.status === 'pending'">确认</el-button>
              <el-button size="small" type="success" @click="completeAppointment(scope.row)" v-if="scope.row.status === 'confirmed'">完成</el-button>
              <el-button size="small" type="danger" @click="cancelAppointment(scope.row)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="filteredAppointments.length"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </div>
    </div>

    <!-- 待办事项视图 -->
    <div v-if="viewMode === 'todos'" class="todos-section">
      <div class="todos-container bg-white rounded-lg shadow-sm">
        <div class="p-6 border-b border-gray-200">
          <div class="flex justify-between items-center">
            <h2 class="text-lg font-bold text-gray-800">待办事项管理</h2>
            <div class="flex gap-3">
              <el-select v-model="todoFilter" placeholder="筛选状态" style="width: 150px">
                <el-option label="全部" value="" />
                <el-option label="未完成" value="pending" />
                <el-option label="已完成" value="completed" />
                <el-option label="高优先级" value="high" />
              </el-select>
            </div>
          </div>
        </div>
        
        <div class="p-6">
          <div class="todos-list space-y-4">
            <div v-for="todo in filteredTodos" :key="todo.id" 
                 :class="['todo-item p-4 border rounded-lg transition-all cursor-pointer',
                         todo.completed ? 'bg-gray-50 border-gray-200' : 'bg-white border-gray-300 hover:border-blue-300']"
                 @click="editTodo(todo)">
              <div class="flex items-start space-x-3">
                <el-checkbox 
                  v-model="todo.completed" 
                  @change="toggleTodo(todo)"
                  @click.stop
                ></el-checkbox>
                <div class="flex-1">
                  <div class="flex items-center justify-between mb-2">
                    <h4 :class="['font-medium', todo.completed ? 'text-gray-500 line-through' : 'text-gray-800']">
                      {{ todo.title }}
                    </h4>
                    <div class="flex items-center space-x-2">
                      <span :class="getPriorityClass(todo.priority)" class="text-xs px-2 py-1 rounded">
                        {{ getPriorityText(todo.priority) }}
                      </span>
                      <span :class="['text-xs', isOverdue(todo.dueDate) ? 'text-red-500' : 'text-gray-500']">
                        {{ formatDate(todo.dueDate) }}
                      </span>
                    </div>
                  </div>
                  <p :class="['text-sm', todo.completed ? 'text-gray-400' : 'text-gray-600']">
                    {{ todo.description }}
                  </p>
                  <div class="flex items-center justify-between mt-2">
                    <span class="text-xs text-gray-500">
                      关联案件：{{ todo.caseNumber || '无' }}
                    </span>
                    <span class="text-xs text-gray-500">
                      创建时间：{{ formatDate(todo.createdAt) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            
            <div v-if="filteredTodos.length === 0" class="text-center py-12 text-gray-500">
              <i class="fas fa-clipboard-list text-4xl mb-4"></i>
              <p>暂无待办事项</p>
              <el-button type="primary" @click="showAddTodoDialog = true" class="mt-4">
                创建第一个待办事项
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加待办事项对话框 -->
    <el-dialog v-model="showAddTodoDialog" title="新建待办事项" width="50%">
      <el-form :model="newTodo" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="newTodo.title" placeholder="请输入待办事项标题"></el-input>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="newTodo.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入详细描述"
          ></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select v-model="newTodo.priority" style="width: 100%">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期">
              <el-date-picker
                v-model="newTodo.dueDate"
                type="datetime"
                placeholder="选择截止日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="关联案件">
          <el-input v-model="newTodo.caseNumber" placeholder="请输入案件编号（可选）"></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddTodoDialog = false">取消</el-button>
          <el-button type="primary" @click="addTodo">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑待办事项对话框 -->
    <el-dialog v-model="showEditTodoDialog" title="编辑待办事项" width="50%">
      <el-form :model="editingTodo" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="editingTodo.title" placeholder="请输入待办事项标题"></el-input>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="editingTodo.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入详细描述"
          ></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select v-model="editingTodo.priority" style="width: 100%">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期">
              <el-date-picker
                v-model="editingTodo.dueDate"
                type="datetime"
                placeholder="选择截止日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="关联案件">
          <el-input v-model="editingTodo.caseNumber" placeholder="请输入案件编号（可选）"></el-input>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-checkbox v-model="editingTodo.completed">已完成</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditTodoDialog = false">取消</el-button>
          <el-button @click="deleteTodo(editingTodo.id)" type="danger">删除</el-button>
          <el-button type="primary" @click="updateTodo">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加预约对话框 -->
    <el-dialog v-model="showAddDialog" title="新建预约" width="60%">
      <el-form :model="newAppointment" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名">
              <el-input v-model="newAppointment.clientName" placeholder="请输入客户姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="newAppointment.contact" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约类型">
              <el-select v-model="newAppointment.type" placeholder="请选择预约类型" style="width: 100%">
                <el-option label="法律咨询" value="consultation"></el-option>
                <el-option label="案件委托" value="commission"></el-option>
                <el-option label="合同审查" value="contract"></el-option>
                <el-option label="其他服务" value="other"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约时长">
              <el-select v-model="newAppointment.duration" placeholder="预约时长" style="width: 100%">
                <el-option label="30分钟" :value="30"></el-option>
                <el-option label="60分钟" :value="60"></el-option>
                <el-option label="90分钟" :value="90"></el-option>
                <el-option label="120分钟" :value="120"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="预约时间">
          <el-date-picker
            v-model="newAppointment.scheduledDate"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="预约说明">
          <el-input
            v-model="newAppointment.description"
            type="textarea"
            :rows="3"
            placeholder="请输入预约说明"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="addAppointment">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AppointmentManagement',
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const viewMode = ref('list')
    const selectedDate = ref(new Date())
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const showAddDialog = ref(false)
    
    const filters = reactive({
      status: '',
      type: '',
      dateRange: []
    })
    
    const newAppointment = reactive({
      clientName: '',
      contact: '',
      type: '',
      duration: 60,
      scheduledDate: '',
      description: ''
    })
    
    // 模拟预约数据
    const appointments = ref([
      {
        id: 1,
        appointmentNo: 'APT-2024-001',
        clientName: '张先生',
        contact: '13800138001',
        type: 'consultation',
        scheduledDate: '2024-01-25 14:00:00',
        duration: 60,
        status: 'confirmed',
        description: '追尾事故赔偿问题咨询，对方全责但保险公司拒赔'
      },
      {
        id: 2,
        appointmentNo: 'APT-2024-002',
        clientName: '李女士',
        contact: '13800138002',
        type: 'commission',
        scheduledDate: '2024-01-25 16:00:00',
        duration: 90,
        status: 'pending',
        description: '行人被撞伤残案件委托，需要起诉肇事司机和保险公司'
      },
      {
        id: 3,
        appointmentNo: 'APT-2024-003',
        clientName: '王总',
        contact: '13800138003',
        type: 'consultation',
        scheduledDate: '2024-01-26 10:00:00',
        duration: 120,
        status: 'completed',
        description: '公司车辆交通事故责任划分咨询，员工驾驶公司车辆发生事故'
      },
      {
        id: 4,
        appointmentNo: 'APT-2024-004',
        clientName: '赵女士',
        contact: '13800138004',
        type: 'consultation',
        scheduledDate: '2024-01-26 15:00:00',
        duration: 60,
        status: 'confirmed',
        description: '电动车事故责任认定争议，交警认定同等责任不服'
      },
      {
        id: 5,
        appointmentNo: 'APT-2024-005',
        clientName: '陈先生',
        contact: '13800138005',
        type: 'commission',
        scheduledDate: '2024-01-27 09:00:00',
        duration: 90,
        status: 'pending',
        description: '酒驾撞死人案件家属委托，要求民事赔偿'
      },
      {
        id: 6,
        appointmentNo: 'APT-2024-006',
        clientName: '刘老板',
        contact: '13800138006',
        type: 'consultation',
        scheduledDate: '2024-01-27 14:30:00',
        duration: 60,
        status: 'confirmed',
        description: '货车侧翻事故，咨询是否可以向货主追偿超载责任'
      }
    ])
    
    // 计算属性
    const filteredAppointments = computed(() => {
      let result = appointments.value
      
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(item =>
          item.appointmentNo.toLowerCase().includes(keyword) ||
          item.clientName.toLowerCase().includes(keyword)
        )
      }
      
      if (filters.status) {
        result = result.filter(item => item.status === filters.status)
      }
      
      if (filters.type) {
        result = result.filter(item => item.type === filters.type)
      }
      
      if (filters.dateRange && filters.dateRange.length === 2) {
        result = result.filter(item => {
          const appointmentDate = new Date(item.scheduledDate)
          return appointmentDate >= filters.dateRange[0] && appointmentDate <= filters.dateRange[1]
        })
      }
      
      return result
    })
    
    const totalAppointments = computed(() => appointments.value.length)
    const todayAppointments = computed(() => {
      const today = dayjs().format('YYYY-MM-DD')
      return appointments.value.filter(a => dayjs(a.scheduledDate).format('YYYY-MM-DD') === today).length
    })
    const completedAppointments = computed(() => appointments.value.filter(a => a.status === 'completed').length)
    const urgentAppointments = computed(() => appointments.value.filter(a => a.status === 'pending').length)
    
    // 方法
    const refreshData = () => {
      ElMessage.success('数据已刷新')
    }
    
    const applyFilters = () => {
      currentPage.value = 1
    }
    
    const clearFilters = () => {
      Object.assign(filters, {
        status: '',
        type: '',
        dateRange: []
      })
      searchKeyword.value = ''
      currentPage.value = 1
    }
    
    const getDayAppointments = (day) => {
      return appointments.value.filter(a => dayjs(a.scheduledDate).format('YYYY-MM-DD') === day)
    }
    
    const viewAppointment = (appointment) => {
      router.push(`/lawyer/appointment/${appointment.id}`)
    }
    
    const confirmAppointment = async (appointment) => {
      try {
        await ElMessageBox.confirm('确定要确认这个预约吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        appointment.status = 'confirmed'
        ElMessage.success('预约已确认')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('确认失败')
        }
      }
    }
    
    const completeAppointment = async (appointment) => {
      try {
        await ElMessageBox.confirm('确定要标记这个预约为已完成吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        })
        
        appointment.status = 'completed'
        ElMessage.success('预约已完成')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }
    
    const cancelAppointment = async (appointment) => {
      try {
        await ElMessageBox.confirm('确定要取消这个预约吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        appointment.status = 'cancelled'
        ElMessage.success('预约已取消')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消失败')
        }
      }
    }
    
    const addAppointment = () => {
      if (!newAppointment.clientName || !newAppointment.contact || !newAppointment.type || !newAppointment.scheduledDate) {
        ElMessage.error('请填写必填字段')
        return
      }
      
      const id = Math.max(...appointments.value.map(a => a.id)) + 1
      appointments.value.unshift({
        id,
        appointmentNo: `APT-2024-${String(id).padStart(3, '0')}`,
        clientName: newAppointment.clientName,
        contact: newAppointment.contact,
        type: newAppointment.type,
        scheduledDate: dayjs(newAppointment.scheduledDate).format('YYYY-MM-DD HH:mm:ss'),
        duration: newAppointment.duration,
        status: 'pending',
        description: newAppointment.description
      })
      
      showAddDialog.value = false
      Object.assign(newAppointment, {
        clientName: '',
        contact: '',
        type: '',
        duration: 60,
        scheduledDate: '',
        description: ''
      })
      
      ElMessage.success('预约创建成功')
    }
    
    const getTypeColor = (type) => {
      const colorMap = {
        consultation: 'primary',
        commission: 'success',
        contract: 'warning',
        other: 'info'
      }
      return colorMap[type] || ''
    }
    
    const getTypeName = (type) => {
      const nameMap = {
        consultation: '法律咨询',
        commission: '案件委托',
        contract: '合同审查',
        other: '其他服务'
      }
      return nameMap[type] || type
    }
    
    const getStatusColor = (status) => {
      const colorMap = {
        pending: 'warning',
        confirmed: 'primary',
        'in-progress': 'info',
        completed: 'success',
        cancelled: 'danger'
      }
      return colorMap[status] || ''
    }
    
    const getStatusName = (status) => {
      const nameMap = {
        pending: '待确认',
        confirmed: '已确认',
        'in-progress': '进行中',
        completed: '已完成',
        cancelled: '已取消'
      }
      return nameMap[status] || status
    }
    
    const formatDateTime = (dateTime) => {
      return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
    }
    
    // 待办事项相关数据
    const showAddTodoDialog = ref(false)
    const showEditTodoDialog = ref(false)
    const todoFilter = ref('')
    
    const newTodo = reactive({
      title: '',
      description: '',
      priority: 'medium',
      dueDate: '',
      caseNumber: ''
    })
    
    const editingTodo = reactive({
      id: null,
      title: '',
      description: '',
      priority: 'medium',
      dueDate: '',
      caseNumber: '',
      completed: false
    })
    
    // 模拟待办事项数据
    const todos = ref([
      {
        id: 1,
        title: '准备庭审材料',
        description: '张先生追尾案庭审材料准备，包括现场照片、维修发票等',
        priority: 'high',
        dueDate: '2024-01-26 09:00:00',
        caseNumber: 'CASE-2024-001',
        completed: false,
        createdAt: '2024-01-20 10:00:00'
      },
      {
        id: 2,
        title: '联系保险公司',
        description: '就李小姐案件联系对方保险公司，确认理赔进度',
        priority: 'medium',
        dueDate: '2024-01-25 16:00:00',
        caseNumber: 'CASE-2024-002',
        completed: false,
        createdAt: '2024-01-21 14:30:00'
      },
      {
        id: 3,
        title: '整理证据材料',
        description: '王老板货车侧翻案证据整理，包括行车记录仪、货物清单等',
        priority: 'medium',
        dueDate: '2024-01-28 10:00:00',
        caseNumber: 'CASE-2024-003',
        completed: true,
        createdAt: '2024-01-18 09:15:00'
      },
      {
        id: 4,
        title: '调解谈判准备',
        description: '赵女士工伤案调解谈判准备，收集相关赔偿标准',
        priority: 'high',
        dueDate: '2024-01-27 14:00:00',
        caseNumber: 'CASE-2024-004',
        completed: false,
        createdAt: '2024-01-22 11:20:00'
      },
      {
        id: 5,
        title: '法律文书起草',
        description: '陈先生酒驾案民事起诉书起草',
        priority: 'medium',
        dueDate: '2024-01-29 17:00:00',
        caseNumber: 'CASE-2024-005',
        completed: false,
        createdAt: '2024-01-23 16:45:00'
      }
    ])
    
    // 待办事项计算属性
    const filteredTodos = computed(() => {
      let result = todos.value
      
      if (todoFilter.value === 'pending') {
        result = result.filter(todo => !todo.completed)
      } else if (todoFilter.value === 'completed') {
        result = result.filter(todo => todo.completed)
      } else if (todoFilter.value === 'high') {
        result = result.filter(todo => todo.priority === 'high' && !todo.completed)
      }
      
      return result
    })
    
    const totalTodos = computed(() => todos.value.filter(todo => !todo.completed).length)
    
    // 待办事项方法
    const addTodo = () => {
      if (!newTodo.title) {
        ElMessage.error('请填写待办事项标题')
        return
      }
      
      const id = Math.max(...todos.value.map(t => t.id)) + 1
      todos.value.unshift({
        id,
        title: newTodo.title,
        description: newTodo.description,
        priority: newTodo.priority,
        dueDate: newTodo.dueDate ? dayjs(newTodo.dueDate).format('YYYY-MM-DD HH:mm:ss') : '',
        caseNumber: newTodo.caseNumber,
        completed: false,
        createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
      })
      
      showAddTodoDialog.value = false
      Object.assign(newTodo, {
        title: '',
        description: '',
        priority: 'medium',
        dueDate: '',
        caseNumber: ''
      })
      
      ElMessage.success('待办事项创建成功')
    }
    
    const editTodo = (todo) => {
      Object.assign(editingTodo, {
        id: todo.id,
        title: todo.title,
        description: todo.description,
        priority: todo.priority,
        dueDate: todo.dueDate ? new Date(todo.dueDate) : '',
        caseNumber: todo.caseNumber,
        completed: todo.completed
      })
      showEditTodoDialog.value = true
    }
    
    const updateTodo = () => {
      if (!editingTodo.title) {
        ElMessage.error('请填写待办事项标题')
        return
      }
      
      const todoIndex = todos.value.findIndex(t => t.id === editingTodo.id)
      if (todoIndex !== -1) {
        todos.value[todoIndex] = {
          ...todos.value[todoIndex],
          title: editingTodo.title,
          description: editingTodo.description,
          priority: editingTodo.priority,
          dueDate: editingTodo.dueDate ? dayjs(editingTodo.dueDate).format('YYYY-MM-DD HH:mm:ss') : '',
          caseNumber: editingTodo.caseNumber,
          completed: editingTodo.completed
        }
      }
      
      showEditTodoDialog.value = false
      ElMessage.success('待办事项更新成功')
    }
    
    const toggleTodo = (todo) => {
      todo.completed = !todo.completed
      ElMessage.success(todo.completed ? '待办事项已完成' : '待办事项标记为未完成')
    }
    
    const deleteTodo = async (todoId) => {
      try {
        await ElMessageBox.confirm('确定要删除这个待办事项吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const todoIndex = todos.value.findIndex(t => t.id === todoId)
        if (todoIndex !== -1) {
          todos.value.splice(todoIndex, 1)
          ElMessage.success('待办事项删除成功')
          showEditTodoDialog.value = false
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const getPriorityClass = (priority) => {
      const classMap = {
        low: 'bg-green-100 text-green-600',
        medium: 'bg-yellow-100 text-yellow-600',
        high: 'bg-red-100 text-red-600'
      }
      return classMap[priority] || ''
    }
    
    const getPriorityText = (priority) => {
      const textMap = {
        low: '低',
        medium: '中',
        high: '高'
      }
      return textMap[priority] || priority
    }
    
    const formatDate = (date) => {
      if (!date) return '无截止日期'
      return dayjs(date).format('MM-DD HH:mm')
    }
    
    const isOverdue = (dueDate) => {
      if (!dueDate) return false
      return dayjs(dueDate).isBefore(dayjs())
    }
    
    return {
      loading,
      viewMode,
      selectedDate,
      searchKeyword,
      currentPage,
      pageSize,
      showAddDialog,
      filters,
      newAppointment,
      filteredAppointments,
      totalAppointments,
      todayAppointments,
      completedAppointments,
      urgentAppointments,
      refreshData,
      applyFilters,
      clearFilters,
      getDayAppointments,
      viewAppointment,
      confirmAppointment,
      completeAppointment,
      cancelAppointment,
      addAppointment,
      getTypeColor,
      getTypeName,
      getStatusColor,
      getStatusName,
      formatDateTime,
      // 待办事项相关
      showAddTodoDialog,
      showEditTodoDialog,
      todoFilter,
      newTodo,
      editingTodo,
      todos,
      filteredTodos,
      totalTodos,
      addTodo,
      editTodo,
      updateTodo,
      toggleTodo,
      deleteTodo,
      getPriorityClass,
      getPriorityText,
      formatDate,
      isOverdue
    }
  }
}
</script>

<style scoped>
.appointment-management {
  padding: 24px;
  background-color: #f9fafb;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 视图控制 */
.view-controls {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.view-mode-selector {
  background: white;
  padding: 4px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 统计区域 */
.stats-section {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon i {
  font-size: 24px;
}

.stat-content h3 {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 4px 0;
  color: #1f2937;
}

.stat-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 筛选区域 */
.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 300px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 日历视图 */
.calendar-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.calendar-container {
  width: 100%;
}

.calendar-day {
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.day-number {
  font-weight: 600;
  margin-bottom: 4px;
}

.appointments-count {
  font-size: 12px;
  color: #3b82f6;
  background: #eff6ff;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 列表视图 */
.appointment-list-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .appointment-management {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .search-box {
    min-width: auto;
  }
}

/* 待办事项样式 */
.todos-section {
  margin-top: 24px;
}

.todos-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.todo-item {
  transition: all 0.2s ease;
  border: 1px solid #e5e7eb;
}

.todo-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.todo-item.completed {
  opacity: 0.7;
}

.todo-item .el-checkbox {
  margin-right: 12px;
}

.todo-item h4 {
  font-size: 16px;
  margin: 0;
  line-height: 1.5;
}

.todo-item p {
  margin: 8px 0 0 0;
  line-height: 1.4;
}

/* 优先级标签样式 */
.bg-green-100 {
  background-color: #dcfce7;
}

.text-green-600 {
  color: #16a34a;
}

.bg-yellow-100 {
  background-color: #fef3c7;
}

.text-yellow-600 {
  color: #d97706;
}

.bg-red-100 {
  background-color: #fee2e2;
}

.text-red-600 {
  color: #dc2626;
}

.bg-purple-100 {
  background-color: #f3e8ff;
}

.text-purple-600 {
  color: #9333ea;
}

/* 其他工具类样式 */
.space-y-4 > * + * {
  margin-top: 1rem;
}

.line-through {
  text-decoration: line-through;
}

.text-gray-400 {
  color: #9ca3af;
}

.text-gray-500 {
  color: #6b7280;
}

.text-gray-600 {
  color: #4b5563;
}

.text-gray-800 {
  color: #1f2937;
}

.border-gray-200 {
  border-color: #e5e7eb;
}

.border-gray-300 {
  border-color: #d1d5db;
}

.hover\:border-blue-300:hover {
  border-color: #93c5fd;
}

.bg-gray-50 {
  background-color: #f9fafb;
}
</style> 